﻿using System;
using System.Data;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections.Generic;

using PluginInstanceAlias = EpisodeWizard.Core.PluginManager<EpisodeWizard.Core.QueryPlugin>.PluginInstance;


namespace EpisodeWizard.App.WizardPages
{

	public partial class WizardPagePlugins : CoreUI.WizardPage
	{
		public WizardPagePlugins()
		{
			InitializeComponent();
		}

		/// <summary>
		/// On entering the page, fill the list with plugins from the plugin folder
		/// </summary>
		private void WizardPagePlugins_EnterPage()
		{
			listPlugins.Items.Clear();
			foreach (PluginInstanceAlias Plugin in Core.Program.GetInstance().Plugins)
			{
				ListViewItem LVI = new ListViewItem(Plugin.Instance.Name);
				LVI.SubItems.Add(Plugin.Instance.Description);
				LVI.Checked = Plugin.Active;
				LVI.Tag = Plugin;
				LVI.Checked = true;
				listPlugins.Items.Add(LVI);
			}
		}

		private void listPlugins_ItemChecked(object sender, ItemCheckedEventArgs e)
		{
			PluginInstanceAlias PI = (PluginInstanceAlias)e.Item.Tag;
			PI.Active = e.Item.Checked;
		}


		/// <summary>
		/// Initialize the selected plugins
		/// </summary>
		private void WizardPagePlugins_LeavePage()
		{
			CoreUI.ThreadHelpers.StartThreadedAction(new ThreadedInit(), true);
		}


		/// <summary>
		/// Make sure at least one plugin is selected before going to the next page
		/// </summary>
		private void WizardPagePlugins_ValidatePage(ValidatePageEventArgs e)
		{
			bool AtLeastOne = false;
			foreach (PluginInstanceAlias PI in Core.Program.GetInstance().Plugins)
			{
				if (PI.Active)
				{
					AtLeastOne = true;
				}
			}
			if (!AtLeastOne)
			{
				MessageBox.Show("Please select at least one plugin", "Validation", MessageBoxButtons.OK, MessageBoxIcon.Information);
				e.Cancel = true;
			}
		}

	}

	/// <summary>
	/// Initialize the plugins in a separate thread
	/// So that the UI can still update properly
	/// </summary>
	public class ThreadedInit : Core.ThreadedAction
	{
		public override void Action()
		{
			OnStart();

			foreach (PluginInstanceAlias PI in Core.Program.GetInstance().Plugins)
			{
				if (CancelRequest)
				{
					break;
				}

				if (PI.Active)
				{
					PI.Instance.InitializeProgress += new Core.QueryPlugin.InitializeProgressHandler(InitializeProgress);
					PI.Instance.Initialize();
				}
			}

			OnEnd();
		}

		private void InitializeProgress(int Percent, string Text1, string Text2)
		{
			OnProgress(Percent, Text1, Text2);
		}

	}


}
